﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using MongoDB.Bson.IO;

namespace Framework.Serializer
{
    class MongoBsonSerializer : BytesSerializeBase
    {
        /// <summary>
        /// 序列化为byte[]
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override byte[] Serialize(object obj)
        {
            using (var buffer = new BsonBuffer())
            {
                using (var bsonWriter = BsonWriter.Create(buffer, BsonBinaryWriterSettings.Defaults))
                {
                    MongoDB.Bson.Serialization.BsonSerializer.Serialize(bsonWriter, obj.GetType(), obj, null);
                }
                return buffer.ToByteArray();
            }
        }


        /// <summary>
        /// 反序列化为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public override T DeSerialize<T>(byte[] source)
        {
            return MongoDB.Bson.Serialization.BsonSerializer.Deserialize<T>(source);
        }
    }
    /*
    class MongoJsonSerializer : StringSerializeBase
    {
        /// <summary>
        /// 序列化为byte[]
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override string Serialize(object obj)
        {
            using (var stringWriter = new StringWriter())
            {
                using (var bsonWriter = BsonWriter.Create(stringWriter, JsonWriterSettings.Defaults))
                {
                    MongoDB.Bson.Serialization.BsonSerializer.Serialize(bsonWriter, obj.GetType(), obj, null);
                }
                return stringWriter.ToString();
            }
        }


        /// <summary>
        /// 反序列化为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public override T DeSerialize<T>(string source)
        {
            return MongoDB.Bson.Serialization.BsonSerializer.Deserialize<T>(source);
        }
    }
     * */
}
